1. Imports


In [6]:
# 'generic import' of math module
import math
math.sqrt(25)


Out[6]:
5.0

In [7]:
# import a function
from math import sqrt
sqrt(25)  # no longer have to reference the module


Out[7]:
5.0

In [8]:
# import multiple functions at once
from math import cos, floor

# import all functions in a module (generally discouraged)
from csv import *

# define an alias
import datetime as dt

2. Simple Data Types

Determine type of an object


In [9]:
print(type(2)) #int


<type 'int'>

In [10]:
type(2.0) #float


Out[10]:
float

In [11]:
type("two") #string


Out[11]:
str

In [12]:
type(True) # bool


Out[12]:
bool

In [13]:
type(None) #NoneType


Out[13]:
NoneType

Check if an object is of a given type


In [14]:
isinstance(2.0, float)


Out[14]:
True

In [15]:
isinstance("two", (float, str))


Out[15]:
True

Convert an object to a given type


In [16]:
float(2)


Out[16]:
2.0

In [17]:
int(2.9)


Out[17]:
2

In [18]:
str(2.9)


Out[18]:
'2.9'

Zero, None and empty containers are converted to False:


In [19]:
bool(0)


Out[19]:
False

In [20]:
bool(None)


Out[20]:
False

In [21]:
bool('') # empty string


Out[21]:
False

In [22]:
bool({}) # empty dictionary


Out[22]:
False

Non-Empty containers and non-zeros are converted to True


In [23]:
bool(2)


Out[23]:
True

In [24]:
bool('two')


Out[24]:
True

In [25]:
bool([2])


Out[25]:
True

In [26]:
bool({'key':'val'})


Out[26]:
True

3. Math


In [27]:
10 ** 4 # exponent


Out[27]:
10000

In [28]:
5 % 4 # modulo


Out[28]:
1

In [29]:
# previous versions of python did integer division
# python 3 coerces values into floats
10/4


Out[29]:
2

In [30]:
10 // 4 # floor division


Out[30]:
2

4. Comparisons and Boolean Operations


In [31]:
x = 5

In [32]:
x != 3


Out[32]:
True

In [33]:
x >= 5 and x < 10


Out[33]:
True

In [34]:
x < 5 or x ==5


Out[34]:
True

5. Conditional Statements


In [35]:
if x > 0:
    print('positive')
elif x == 0:
    print('zero')
else:
    print('negative')


positive

In [36]:
#single-line if
if x > 0: print('positive')


positive

In [37]:
#single line if/else statement (ternary operator)
'positive' if x > 0 else 'zero or negative'


Out[37]:
'positive'

6. For Loops and While Loops

range returns a sequence of integers from 0 to n-1


In [38]:
# includes the start value but not the stop value [start, end)
range(0,3) #[0, ,1, 2]
rng = range(0,3)
list(rng)


Out[38]:
[0, 1, 2]

In [39]:
# default start is 0
rng = range(3)
list(rng)


Out[39]:
[0, 1, 2]

In [40]:
#third argument is a step value
rng = range(0,5,2)
list(rng)


Out[40]:
[0, 2, 4]

for loops:


In [41]:
# not the recommended style
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
    print(fruits[i].upper())


APPLE
BANANA
CHERRY

In [42]:
# recommended style
for fruit in fruits:
    print(fruit.upper())


APPLE
BANANA
CHERRY

In [43]:
# iterate through two things at once (using tuple unpacking)
family = {'dad':'homer', 'mom':'marge', 'size':6}
for key, value in family.items():
    print( key,value)


('dad', 'homer')
('mom', 'marge')
('size', 6)

In [44]:
# use enumerate if you need to access the index value within the loop
for index,fruit in enumerate(fruits):
    print(index,fruit)


(0, 'apple')
(1, 'banana')
(2, 'cherry')

for/else loop:


In [45]:
for fruit in fruits:
    if fruit == 'banana':
        print('Found the banana!')
        break    # exit the loop and skip the 'else' block
else:
    # this block executes ONLY if the for loop completes without hitting 'break'
    print("Can't find the banana")


Found the banana!

while loop:


In [46]:
count = 0
while count < 5:
    print('printing %s time(s)' % count)
    count += 1


printing 0 time(s)
printing 1 time(s)
printing 2 time(s)
printing 3 time(s)
printing 4 time(s)

7. Slicing


In [ ]:
weekdays = ['mon', 'tues', 'wed', 'thurs', 'fri']

In [ ]:
weekdays[0]

In [ ]:
# elements 0 (inclusive) to 3 (exclusive)
weekdays[0:3]

In [ ]:
# starting point implied to be zero
weekdays[:3]

In [ ]:
# elements 3 (inclusive) through implied end
weekdays[3:]

In [ ]:
# last element
weekdays[-1]

In [ ]:
# eveery second element (step by 2)
weekdays[::2]

In [ ]:
# backwards (step by -1)
weekdays[::-1]

In [ ]:

8. With Statement


In [1]:
# the With statement (like using in C#) is used to issue cleanup code when a variable comes out of scope
class cleanup_thing:
        def __enter__(self):
            self.open=True
            return self
        def __exit__(self, type, value, traceback):
            self.open=False
        def isOpen(self):
            return self.open

with cleanup_thing() as thing:
    print(thing.isOpen())
print(thing.isOpen())


True
False

9. DateTime


In [ ]:
from datetime import datetime
from datetime import timedelta

#get now
datetime.today()

In [ ]:
a = datetime(2012, 9, 23)
a

In [ ]:
b = timedelta(days=2, hours=6)
a+b

In [ ]:
a-b

In [ ]:
d=b+timedelta(hours=4.5)
d.days

In [ ]:
d.seconds

In [ ]:
# total timedelta in seconds
d.total_seconds()

Converting to / from strings


In [ ]:
text = '2012-09-20'
datetime.strptime(text, '%Y-%m-%d')

In [ ]:
z = datetime(2012, 9, 23, 21, 37, 4, 177393)
datetime.strftime(z, '%A %B %d, %Y')

Time Zones


In [ ]:
from pytz import timezone

d = datetime(2012, 12, 21, 9, 30, 0)

# localize the date for Chicago
central = timezone('US/Central')
loc_d = central.localize(d)
print(loc_d)

In [ ]:
# Convert to Bangalore time
bang_d = loc_d.astimezone(timezone('Asia/Kolkata'))
print(bang_d)